package com.lovely602.ai.alibaba.controller.graph;


import com.alibaba.cloud.ai.graph.*;
import com.alibaba.cloud.ai.graph.checkpoint.config.SaverConfig;
import com.alibaba.cloud.ai.graph.checkpoint.constant.SaverConstant;
import com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver;
import com.alibaba.cloud.ai.graph.exception.GraphRunnerException;
import com.alibaba.cloud.ai.graph.exception.GraphStateException;
import com.lovely602.ai.alibaba.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Optional;

/**
 *
 * 工作流测试
 *
 * @author lizhixing
 */
@Slf4j
@RestController
public class ProductGraphController {

    private final CompiledGraph compiledGraph;

    public ProductGraphController(@Qualifier("productAnalysisGraph") StateGraph productAnalysisGraph) throws GraphStateException {
        SaverConfig saverConfig = SaverConfig.builder().register(SaverConstant.MEMORY, new MemorySaver()).build();
        this.compiledGraph = productAnalysisGraph.compile(CompileConfig.builder().saverConfig(saverConfig).build());
    }

    /**
     * 商品工作流
     */
    @GetMapping(value = "/product/enrich")
    public Product enrichProduct(
            @RequestParam(value = "productDesc", defaultValue = "一款高品质、舒适的纯棉T恤，有蓝、红、绿三种颜色可选，适合夏季穿着。") String productDesc) throws GraphRunnerException {
        Map<String, Object> initialState = Map.of("productDesc", productDesc);
        RunnableConfig runnableConfig = RunnableConfig.builder().build();
        Optional<OverAllState> invoke = compiledGraph.invoke(initialState, runnableConfig);
        return (Product) invoke.get().value("finalProduct").orElseThrow();
    }

}
